/*
 * @Autor: 郑祥
 * @Date: 2021-01-19 10:56:49
 * @LastEditTime: 2021-06-03 09:10:22
 * @FilePath: \sybjy\src\components\PictureUpload\index.js
 * @LastEditors: 陈科引
 * @Description: 图片上传
 */
import React, { useState, useEffect } from "react";
import { Modal, Upload, message } from "antd";
import { PlusOutlined } from "@ant-design/icons";
import { baseURL } from "@/axios";

const PictureUpload = (props) => {
	const [fileList, setfileList] = useState([]);
	const [previewVisible, setpreviewVisible] = useState(false);
	const [previewTitle, setpreviewTitle] = useState("");
	const [previewImage, setpreviewImage] = useState("");
	useEffect(() => {
		setfileList(props.fileList);
	}, [props.fileList]);
	const getBase64 = (file) => {
		return new Promise((resolve, reject) => {
			const reader = new FileReader();
			reader.readAsDataURL(file);
			reader.onload = () => resolve(reader.result);
			reader.onerror = (error) => reject(error);
		});
	};
	/**
	 * @author: 郑祥
	 * @param {Object} file
	 * @description: 点击下载文件时的回调
	 *    dataURLtoBlob downloadFile handleDownload 这3个方法将Base64转为blob本地下载
	 */
	// const handleDownload = file => {
	//   let myBlob = dataURLtoBlob(file.thumbUrl)
	//   let myUrl = URL.createObjectURL(myBlob)
	//   downloadFile(myUrl, file.name)
	// }
	// const dataURLtoBlob = (dataurl) => {
	//   let arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
	//     bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
	//   while (n--) {
	//     u8arr[n] = bstr.charCodeAt(n);
	//   }
	//   return new Blob([u8arr], { type: mime });
	// }
	// const downloadFile = (url, name = '1111') => {
	//   let a = document.createElement("a")
	//   a.setAttribute("href", url)
	//   a.setAttribute("download", name)
	//   a.setAttribute("target", "_blank")
	//   let clickEvent = document.createEvent("MouseEvents");
	//   clickEvent.initEvent("click", true, true);
	//   a.dispatchEvent(clickEvent);
	// }
	/**
	 * @author: 郑祥
	 * @param {Object} file
	 * @description: 点击文件链接或预览图标时的回调
	 */
	const handlePreview = async (file) => {
		if (!file.url && !file.preview) {
			file.preview = await getBase64(file.originFileObj);
		}
		setpreviewImage(file.url || file.preview);
		setpreviewVisible(true);
		setpreviewTitle(
			file.name || file.url.substring(file.url.lastIndexOf("/") + 1)
		);
	};
	/**
	 * @author: 郑祥
	 * @param {Object} file
	 * @description: 图片上传前的判断
	 */
	const handleBeforeUpload = (file) => {
		const isJpgOrPng = file.type.includes("image");
		if (!isJpgOrPng) {
			message.error("请上传图片");
		}
		return isJpgOrPng;
	};
	/**
	 * @author: 郑祥
	 * @param {Object} file
	 * @description: 删除图片
	 */
	const handleRemove = (file) => {
		const newFileList = fileList.slice();
		newFileList.splice(fileList.indexOf(file), 1);
		setfileList(newFileList);
		props.onChange(newFileList);
	};
	/**
	 * @author: 郑祥
	 * @param {Object} file
	 * @description: 上传图片
	 */
	const handleChange = (info) => {
		let fileLists = [...info.fileList];
		fileLists = fileLists.map((file) => {
			if (file.response) {
				file.url = file.response.fileName;
				file.id = file.response.id;
			}
			return file;
		});
		setfileList([...fileLists]);
		props.onChange([...fileLists]);
		// const { file } = e
		// if (file.status === 'uploading') {
		//   setfileList([...fileList, file])
		// }
		// if (file.status === 'done') {
		//   if (file.xhr && file.xhr.status === 200) {
		//     file.id = file.response.data.id
		//     file.url = file.response.data.fullUrl
		//     setfileList([...fileList, file])
		//     props.onChange([...fileList, file])
		//   } else {
		//     message.error('上传图片失败!');
		//   }
		// }
	};
	const UploadProps = {
		action: `${baseURL}pdjh/file/upload`,
		// action: `${baseURL}fastdfs/upload`,
		fileList,
		listType: "picture-card",
		onPreview: handlePreview,
		// onDownload: handleDownload,
		onRemove: handleRemove,
		beforeUpload: handleBeforeUpload,
		onChange: handleChange,
		headers: {
			"Auth-Token": JSON.parse(sessionStorage.getItem("userInfo")).token,
		},
		showUploadList: {
			showPreviewIcon: true,
			// showDownloadIcon: true,
			showRemoveIcon: props.disabled ? false : true,
		},
	};
	return (
		<>
			<Upload {...UploadProps}>
				{fileList.length >= props.Leng || props.disabled ? null : (
					<div>
						<PlusOutlined />
						<div style={{ marginTop: 8 }}>图片上传</div>
					</div>
				)}
			</Upload>
			<Modal
				visible={previewVisible}
				title={previewTitle}
				footer={null}
				onCancel={() => {
					setpreviewVisible(false);
					setpreviewImage("");
				}}
			>
				<img alt="example" style={{ width: "100%" }} src={previewImage} />
			</Modal>
		</>
	);
};

export default PictureUpload;
